import axios from 'axios';
import config from '../../build/config';
import Modules from '@/router/module';
import storage from './storage';

const env  = config.env;

/**
 * 工具类
 * @type {{}}
 */
let util = {

};

/**
 * 修改网页title
 * @param title
 */
util.title = function (title) {
    title = title || config.webName;
    window.document.title = title;
};

/**
 * 设置axios配置，增加csrf-token配置
 * @type {string}
 */
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
if (env === 'production') {
    /**
     * Next we will register the CSRF Token as a common header with Axios so that
     * all outgoing HTTP requests automatically have it attached. This is just
     * a simple convenience so we don't have to attach every token manually.
     */

    let token = document.head.querySelector('meta[name="csrf-token"]');
    if (token) {
        axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    } else {
        console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
    }
}

/**
 * ajax baseURL 配置
 * @type {string}
 */
util.ajax = axios.create({
    baseURL: config.ajaxUrl,
    timeout: 60000
});

/**
 * ajax api baseURL 配置
 * @type {string}
 */
const getApiAxios = () => {
    const tokens = storage.get('tokens') || {};
    return axios.create({
        baseURL: config.apiUrl,
        timeout: 60000,
        headers: {
            'Authorization': 'Bearer ' + tokens.access_token
        }
    });
};

util.api = getApiAxios;

util.handleApiException = (e, vm, defaultMessage = '网络请求异常') => {
    console.log(e);
    if (e.response) {
        if (e.response.status == 422) {
            if (e.response.data.hasOwnProperty('errors')) {
                for (let i in e.response.data.errors) {
                    vm.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                }
            }
        } else if (e.response.status == 401) {
            if (e.response.hasOwnProperty('data')) {
                vm.$Notice.error({ title: defaultMessage, desc: e.response.data.message });
            } else {
                vm.$Notice.error({ title: defaultMessage, desc: '用户名或密码错误' });
            }
            // 退出登录
            vm.$store.commit('logout', this);
            vm.$store.commit('clearOpenedSubmenu');
            vm.$store.commit('clearAllTags');
            vm.$router.push({
                name: 'login'
            });
        } else if (e.response.hasOwnProperty('data') && e.response.data.code == 403) {
            vm.$store.commit('removeTag', vm.$route.name);
            vm.$router.push({
                name: 'error-403'
            });
            vm.$Notice.error({ title: defaultMessage, desc: e.response.data.message});
        } else {
            vm.$Notice.error({ title: defaultMessage, desc: e.response.data.message});
        }
    } else {
        vm.$Message.error(defaultMessage);
    }
};

/**
 * 刷新accessToken
 */
util.refreshToken = function () {
    const tokens = storage.get('tokens');
    var form_params = {
        'grant_type': 'refresh_token',
        'client_id': config.appId,
        'client_secret': config.appSecret,
        'refresh_token': tokens.refresh_token,
        'scope': ''
    };

    util.ajax.post('/oauth/token', form_params).then((resp) => {
        storage.set('tokens', resp.data);
        this.$store.dispatch('setTokens', resp.data);
    }).catch((e) => {
        console.log('自动刷新Token失败', e);
    });
};

/**
 * 获取百度地图Key
 * @returns {string}
 */
util.getBMapKey = function () {
  return config.bMapKey;
};

/**
 * 判断数组是否存在另一个数组中
 * @param arr
 * @param targetArr
 * @returns {boolean}
 */
util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

/**
 * 判断数组的任意一个元素是否在目标数据中存在
 * @param arr
 * @param targetArr
 * @returns {boolean}
 */
util.anyInOf = function (arr, targetArr) {
    let res = false;
    arr.map(item => {
        if (targetArr.indexOf(item) >= 0) {
            res = true;
        }
    });
    return res;
};

/**
 * 判断元素是否存在指定数组中
 * @param ele
 * @param targetArr
 * @returns {boolean}
 */
util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function (itAccess, currentAccess) {
    if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

/**
 * 获取模块菜单对象
 */
util.getModuleMenuList = function () {
    let menuList = [];

    for (let i in Modules) {
        menuList.push(Modules[i].module);
    }

    return menuList;
};

/**
 * 获取模块的路由列表对象
 * @param name
 * @returns {{}}
 */
util.getModuleAppRoutersByName = function (name) {
    for (let i in Modules) {
        if (name == Modules[i].module.name) {
            return Modules[i].router;
        }
    }
    return {};
};

/**
 * 根据路由名称获取路由对象
 * @param routers
 * @param name
 * @returns {{}}
 */
util.getRouterObjByName = function (routers, name) {
    let routerObj = {};
    routers.forEach(item => {
        if (item.name === 'otherRouter') {
            item.children.forEach((child, i) => {
                if (child.name === name) {
                    routerObj = item.children[i];
                }
            });
        } else {
            if (item.children.length === 1) {
                if (item.children[0].name === name) {
                    routerObj = item.children[0];
                }
            } else {
                item.children.forEach((child, i) => {
                    if (child.name === name) {
                        routerObj = item.children[i];
                    }
                });
            }
        }
    });
    return routerObj;
};

util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.app.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '',
                name: 'home_index'
            }
        ];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.app.routers.filter(item => {
            if (item.children.length <= 1) {
                return item.children[0].name === name;
            } else {
                let i = 0;
                let childArr = item.children;
                let len = childArr.length;
                while (i < len) {
                    if (childArr[i].name === name) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        })[0];
        if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '',
                    name: 'home_index'
                }
            ];
        } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: name
                }
            ];
        } else {
            let childObj = currentPathObj.children.filter((child) => {
                return child.name === name;
            })[0];
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: childObj.title,
                    path: currentPathObj.path + '/' + childObj.path,
                    name: name
                }
            ];
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) {  // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.app.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        if (tag) {
            tag = tag.children ? tag.children[0] : tag;
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

util.fullscreenEvent = function (vm) {
    vm.$store.commit('initCachepage');
    // 权限菜单过滤相关
    vm.$store.commit('updateMenulist', vm.$store.state.app.currentModuleName);
    // 全屏相关
};

export default util;
